package com.ruoyi.web.controller.project;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.service.IDemandService;
import com.ruoyi.system.service.ITopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 课题Controller
 *
 * @author EdwardXRX
 * @date 2024-04-12
 */
@RestController
@RequestMapping("/project/topic")
public class TopicController extends BaseController {
    @Autowired
    private ITopicService topicService;

    @Autowired
    private IDemandService demandService;
    /**
     * 查询课题列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Project project) {
        startPage();
        project.setType(2);
        Long userId = getUserId();
        List<Project> list = new ArrayList<>();
        if (getLoginUser().getUserId() == 1) {
            list = topicService.selectProjectList(project);
        } else {
            list = topicService.selectProjectListByUserId(userId);
        }
        return getDataTable(list);
    }


    @GetMapping("/listTopicByClickNum")
    public TableDataInfo listTopicByClickNum(Project project) {
        startPage();
        project.setType(2);
        Long userId = getUserId();
        List<Project> list = new ArrayList<>();
        list = topicService.listTopicByClickNum();
        return getDataTable(list);
    }



    /**
     * 导出课题列表
     */
    @PreAuthorize("@ss.hasPermi('project:topic:export')")
    @Log(title = "课题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Project project) {
        List<Project> list = topicService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        util.exportExcel(response, list, "课题数据");
    }

    /**
     * 获取课题详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:topic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(topicService.selectProjectById(id));
    }

    /**
     * 新增课题
     */
    @PreAuthorize("@ss.hasPermi('project:topic:add')")
    @Log(title = "课题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Project topic) {
        Long userId = getUserId();
        //设置为type为需求收集
        topic.setType(2);
        //直接设置审核员为两个管理员
        //胡昊
        topic.setChecker1(1000043642L);
        //吴兆发
        topic.setChecker2(1000068884L);
        topic.setClickNum(0);
        topic.setUserId(userId);
        topic.setCreateTime(new Date());
        //设置为不可见
        topic.setIsShow(0);
        //设置新建的状态
        topic.setState(0);
        return toAjax(topicService.insertProject(topic));
    }

    /**
     * 修改课题
     */
    @PreAuthorize("@ss.hasPermi('project:topic:edit')")
    @Log(title = "课题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Project project) {
        return toAjax(topicService.updateProject(project));
    }

    /**
     * 删除课题
     */
    @PreAuthorize("@ss.hasPermi('project:topic:remove')")
    @Log(title = "课题", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(topicService.deleteProjectByIds(ids));
    }


    /**
     * 获取上一个需求详细信息
     */
    @GetMapping(value = "/getPreProject/{id}")
    public AjaxResult getPreProject(@PathVariable("id") Long id) {
        Long userId = getUserId();
        Project preProject = new Project();
        if (getLoginUser().getUserId() == 1) {
            // 获取全部列表数据中的上一个项目
            preProject = topicService.getPreProject(id);
        } else {
            List<Project> userProjects = topicService.selectProjectByUserId(userId);
            Long index = findIndexById(userProjects, id);
            if (index != null && index > 0) {
                preProject = userProjects.get(index.intValue() + 1);
            } else {
                // 如果找不到上一个项目，返回一个默认项目
                preProject.setId(-1L);
                preProject.setName("无");
            }
        }
        return success(preProject);
    }

    private Long findIndexById(List<Project> userProjects, Long id) {
        for (int i = 0; i < userProjects.size(); i++) {
            if (userProjects.get(i).getId().equals(id)) {
                return (long) i; // 返回找到的项目在列表中的索引
            }
        }
        return null;
    }

    /**
     * 获取下一个详细信息
     */
    @GetMapping(value = "/getNextProject/{id}")
    public AjaxResult getNextProject(@PathVariable("id") Long id) {
        Long userId = getUserId();
        Project nextProject = new Project();
        if (getLoginUser().getUserId() == 1) {
            nextProject = topicService.getNextProject(id);
        } else {
            List<Project> userProjects = topicService.selectProjectByUserId(userId);
            Long index = findIndexById(userProjects, id);
            if (index != null && index > 0) {
                nextProject = userProjects.get(index.intValue() - 1);
            } else {
                nextProject.setId(-1L);
                nextProject.setName("无");
            }
        }
        return success(nextProject);
    }



}
